const app = getApp();
const token = wx.getStorageSync('token');
Page({

  /**
   * 页面的初始数据
   */
  data: {
      book: {},
      text: "<",
      url: '',
      userId: '',
      collection: [],
      isFavorited: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      
      this.setData({
          url: app.imgUrl
      })
      this.getBybookId(options)
      this.getHoppy(options)
      wx.stopPullDownRefresh()
  },
  onPullDownRefresh(){
    this.onLoad()
},
  // 处理收藏与取消收藏
toggleFavorite(e) {
  const bookId = e.currentTarget.dataset.id;
  const isFavorited = this.data.isFavorited;
  if(!token){
    wx.showToast({
      title: '你还没有登录',
      icon: 'error'
    })
    return
  }
  console.log(isFavorited)
  if(isFavorited==0){
    this.hoppyBook(bookId)
    this.setData({
      isFavorited:1
    })
  }else{
    this.cancelBook(bookId)
    this.setData({
      isFavorited:0
    })
  }
},
hoppyBook(bookId) {
  const app = getApp();
        wx.request({
          url: `${app.apiUrl}/collection/hope`,
          method: 'POST',
          header:{
            "token":token
          },
          data: { 
            "bookId":bookId
           },
          success: (res) => {
            if (res.data.code === 1) {
              wx.showToast({ title: '收藏成功', icon: 'success' });
            } else {
              wx.showToast({ title: '收藏失败', icon: 'error' });
            }
          }
        });
      
    
  
},
// 取消收藏图书方法
cancelBook(bookId) {
  const app = getApp();
  wx.showModal({
    title: '取消收藏',
    content: '确定要取消收藏此图书吗？',
    success: (res) => {
      if (res.confirm) {
        wx.request({
          url: `${app.apiUrl}/collection/${bookId}`,
          method: 'DELETE',
          header:{
            "token":token
          },
          data: {  },
          success: (res) => {
            if (res.data.code === 1) {
              wx.showToast({ title: '取消收藏', icon: 'success' });
            } else {
              wx.showToast({ title: '取消收藏', icon: 'error' });
            }
          }
        });
      }
    }
  });
},
getHoppy(e){
  const id = e.id
  wx.request({
    url: `${app.apiUrl}/collection/${id}`,
    method: 'GET',
    header:{
      "token":token
    },
    data: {  },
    success: (res) => {
      console.log(res)
      if (res.data.code === 1) {
          this.setData({
            isFavorited:res.data.data
          })
      } 
    }
  });
},
  getBybookId(e) {
      const id = e.id
      wx.request({
          url: app.apiUrl + '/books/' + id ,
          method: "GET",
          success: res => {
              this.setData({
                  book: res.data.data
              })
          }
      })
  },
  checkout() {
    console.log("checkout")
    const token = wx.getStorageSync('token'); 
    let bookList = []
    let book = this.data.book
    book.bookId = this.data.book.id
    book.quantity = 1
    console.log(book)
    bookList.push(book)
  wx.request({ 
      url: app.apiUrl + '/orders/save', 
      method: 'POST', 
      header: { 
        token: token, 
      }, 
      data: { 
        "items": bookList, 
        
      }, success:res=>{
        console.log(res)
        wx.navigateTo({
          url: '/pages/orders/index/index?orderId=' + res.data.data,
        });
      }
      })
    },
  addCart(event) {
    const bookId = event.currentTarget.dataset.id; // 获取 bookId
    this.updateCart(bookId, 1); // 更新后端购物车
  },
  updateCart(bookId, quantityChange) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
      });
      return;
    }

    wx.request({
      url: app.apiUrl + '/cart/add',
      method: 'POST',
      header: {
        token: token,
      },
      data: {
        bookId,
        quantity: quantityChange,
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
          });
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'error',
        });
      },
    });
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
      this.onLoad()
  },


})